package skean.yzsm.com.androidvideocache;

import android.text.TextUtils;

import com.danikula.videocache.ProxyCacheUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class VideoNameGenerator {

    private static final int MAX_EXTENSION_LENGTH = 4;
    public static final String TEMP_POSTFIX = ".download";

    public static String generate(String url) {
        String extension = getExtension(url);
        String name = computeMD5(url);
        return TextUtils.isEmpty(extension) ? name : name + "." + extension;
    }

    private static String getExtension(String url) {
        int dotIndex = url.lastIndexOf('.');
        int slashIndex = url.lastIndexOf('/');
        return dotIndex != -1 && dotIndex > slashIndex && dotIndex + 2 + MAX_EXTENSION_LENGTH > url.length() ? url.substring(dotIndex + 1,
                                                                                                                             url.length()) : "";
    }

    public static String computeMD5(String string) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] digestBytes = messageDigest.digest(string.getBytes());
            return bytesToHexString(digestBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

}
